package com.github.aloxc.plugin.restplus.listener;

import com.github.aloxc.plugin.restplus.entity.EnvironmentConfig;
import com.github.aloxc.plugin.restplus.entity.RestConfig;
import com.github.aloxc.plugin.restplus.navigator.RestServicesNavigator;
import com.intellij.openapi.project.Project;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Map;
/**
 * 环境切换
 * @author leero
 */
public class SelectEnvironmentListener implements ActionListener{
    private final static String SPLIT = "   ";

    private Project project;
    public SelectEnvironmentListener(Project project){
        this.project = project;
    }
    @Override
    public void actionPerformed(ActionEvent event) {
        RestConfig config = project.getComponent(RestServicesNavigator.class).getConfig();
        String env = ((JMenuItem) event.getSource()).getText();
        env = env.split(SPLIT)[0];
        if(config != null && config.getEnv() != null && config.getEnv().size() > 0) {
            Map<String, EnvironmentConfig> envMap = config.getEnv();
            int index = 0;
            for (String envName : envMap.keySet()) {
                EnvironmentConfig envConfig = envMap.get(envName);
                if (envConfig.getName().equals(env)) {
                    envConfig.setSelected(true);
                } else {
                    envConfig.setSelected(false);
                }
            }
            config.save(project);
        }
    }
}
